// pages/login/login.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone: '',
    validateCode: '',
    loginType: 1, // 1商户 2员工 3 管理员
    currentTime: 60,
    isSending: false,
    isCheckXY: false,
    showXYialog: false,
    showYSDialog: false,

    loginStyle: 0, //0 验证码登陆 1 账号密码登陆 
    account: '',
    password: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let token = wx.getStorageSync('token')
    let phone = wx.getStorageSync('phone')
    if (token) {
      getApp().savePhone(phone)
      getApp().saveToken(token)
      this.setData({
        phone,
        account: phone
      })
      this.getAccountTypeByAuthMobile(phone)
    }
  },


  getCode: function () {
    const phoneRegExp = /^1[3-9]\d{9}$/;
    const {
      phone
    } = this.data
    if (phone == '' || phone.length < 11 || !phoneRegExp.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }
    this.getSingCode()
    //发送验证码接口
    this.startTime()
  },


  /**
   * 获取订单详情
   */
  getSingCode: function () {
    var that = this;
    let params = {
      type: 1,
      mobile: this.data.phone
    }
    wx.showLoading({
      title: '正在获取验证码',
    })
    getApp().api.getSingCode(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '获取验证码成功',
          icon: 'none'
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '获取验证码失败:' + err.message,
          icon: 'none'
        })
      }
    })

  },

  /**
   * 开始倒计时
   */
  startTime: function () {
    this.setData({
      isSending: true,
      currentTime: 60,
    })
    this.timeInterval()
  },
  /**
   * 倒计时
   */
  timeInterval: function () {
    let that = this
    const timer = setInterval(() => {
      const currentTime = that.data.currentTime;
      if (currentTime > 1) {
        this.setData({
          currentTime: currentTime - 1,
        })
      } else {
        this.setData({
          isSending: false,
          currentTime: 60,
        })
        clearInterval(timer);
      };
    }, 1000);
  },
  inputPhone: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },

  inputCode: function (e) {
    this.setData({
      validateCode: e.detail.value
    })
  },

  inputAccount: function (e) {
    this.setData({
      account: e.detail.value
    })
  },

  inputPassword: function (e) {
    this.setData({
      password: e.detail.value
    })
  },

  /**
   * 获取手机号
   * @param {*} e 
   */
  getPhoneNumber(e) {
    console.log(e.detail.code) // 动态令牌
    console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
    console.log(e.detail.errno) // 错误码（失败时返回）
    //获取手机号
  },

  login: function () {
    let {
      isCheckXY,
      phone,
      validateCode,
      account,
      password,
      loginStyle
    } = this.data

    const phoneRegExp = /^1[3-9]\d{9}$/;
    if (loginStyle == 0) {
      if (phone == '' || phone.length < 11 || !phoneRegExp.test(phone)) {
        wx.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }
      if (validateCode == '' || validateCode.length < 6) {
        wx.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return
      }

      if (!isCheckXY) {
        wx.showToast({
          title: '请勾选同意协议',
          icon: 'none'
        })
        return
      }
      var that = this;
      let params = {
        source: 6,
        code: this.data.validateCode,
        mobile: this.data.phone
      }
      wx.showLoading({
        title: '正在登录中'
      })
      getApp().api.mobileLogin(params, {
        success: function (res) {
          wx.hideLoading()
          wx.showToast({
            title: '登录成功',
            icon: 'none'
          })
          getApp().savePhone(that.data.phone)
          getApp().saveToken(res.data)
          wx.setStorageSync('token', res.data)
          wx.setStorageSync('phone', that.data.phone)
          that.getAccountTypeByAuthMobile(that.data.phone)

        },
        fail: function (err) {
          wx.hideLoading()
          wx.showToast({
            title: '登录失败:' + err.message,
            icon: 'none'
          })
        }
      })
    } else {
      if (account == '' || account.length < 11 || !phoneRegExp.test(account)) {
        wx.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }
      if (password == '') {
        wx.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return
      }


      if (!isCheckXY) {
        wx.showToast({
          title: '请勾选同意协议',
          icon: 'none'
        })
        return
      }
      var that = this;
      let params = {
        source: 6,
        rememberMe: true,
        password: this.data.password,
        mobile: this.data.account
      }
      wx.showLoading({
        title: '正在登录中'
      })
      getApp().api.passwordLogin(params, {
        success: function (res) {
          wx.hideLoading()
          wx.showToast({
            title: '登录成功',
            icon: 'none'
          })
          getApp().savePhone(that.data.account)
          getApp().saveToken(res.data)
          wx.setStorageSync('token', res.data)
          wx.setStorageSync('phone', that.data.account)
          that.getAccountTypeByAuthMobile(that.data.account)

        },
        fail: function (err) {
          wx.hideLoading()
          wx.showToast({
            title: '登录失败:' + err.message,
            icon: 'none'
          })
        }
      })
    }


  },

  getAccountTypeByAuthMobile: function (phone) {
    let params = {
      authMobile: phone,
    }
    getApp().api.getAccountTypeByAuthMobile(params, {
      success: function (res) {
        let accountType = res.data.accountType;
        getApp().saveAccountType(res.data.accountType)
        if (accountType == 2 || accountType == 3 || accountType == 5) { //商户账户 代理商 da和管理员
          wx.switchTab({
            url: '/pages/deviceList/deviceList',
          })
        } else if (accountType == 4 || accountType == 6) { //个体员工(已经绑定了商户的)  或者 员工账户
          wx.redirectTo({
            url: '/pages/selectShop/selectShop',
          })
        } else {
          wx.showToast({
            title: '您的账户暂无无权限使用，请联系平台管理员',
            icon: 'none'
          })
        }
      },
      fail: function (res) {}
    })

  },

  selcetLoginType: function (e) {
    console.log(e)
    this.setData({
      loginType: e.currentTarget.dataset.type
    })
  },

  checkXY: function () {
    this.setData({
      isCheckXY: !this.data.isCheckXY
    })
  },

  showXYDialog: function () {
    this.setData({
      showXYialog: true
    })
  },
  showYSDialog: function () {
    this.setData({
      showYSDialog: true
    })
  },
  cancleDialog: function () {

    this.setData({
      showXYialog: false,
      showYSDialog: false
    })
  },


  selectLoginStyle: function (e) {
    let style = e.currentTarget.dataset.style
    if (style == 0) {
      this.setData({
        loginStyle: e.currentTarget.dataset.style,
        account: '',
        password: ''
      })
    } else {
      this.setData({
        loginStyle: e.currentTarget.dataset.style,
        phone: '',
        code: ''
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})